<script setup>
import { computed, ref } from "vue";
import BranchNode from "./base/BranchNode.vue";
import nodeMixin from "../NodeMixin";

const props = defineProps({
  ...nodeMixin.props,
  moveLn: Boolean,
  moveRn: Boolean,
  isDefault: Boolean
});
const emit = defineEmits(["insertNode", "delete", "select", "moveL", "moveR"]);
const _value = defineModel();

const showErr = ref(false);
const errInfo = ref(null);

defineExpose({ validate });

const content = computed(() => {
  if (props.isDefault) {
    return "其他情况将进入此分支";
  } else {
    let desc = "请设置条件";
    const prop = _value.value.props;
    if (prop.groups.length > 0 && prop.groups[0].conditions.length > 0) {
      desc = "已配置条件";
    }
    return desc;
  }
});

function validate(errs) {
  //校验非默认节点
  showErr.value = true;
  if (!props.isDefault) {
    const prop = _value.value.props;
    if (prop.groups.length === 0) {
      errInfo.value = "请添加条件组";
      errs.push(`条件 ${_value.value.name}未添加条件组`);
      return;
    } else {
      for (let i = 0; i < prop.groups.length; i++) {
        const group = prop.groups[i];
        if (group.conditions.length === 0) {
          errInfo.value = `请给条件组${i}设置条件`;
          errs.push(`${_value.value.name}条件组${i}未添加条件`);
          return;
        }
      }
    }
  }
  showErr.value = false;
}
</script>

<template>
  <BranchNode
    v-model="_value"
    :readonly="props.readonly"
    :show-error="showErr"
    :error-info="errInfo"
    :index="index"
    color="#59B9A4"
    header-icon="share"
    :is-default="props.isDefault"
    :content="content"
    :moveRn="props.moveRn"
    :moveLn="props.moveLn"
    :desc="`优先级 ${props.index + 1}`"
    :flow-inst-id="props.flowInstId"
    :flowHistory="flowHistory"
    @insertNode="type => emit('insertNode', type)"
    @move-l="emit('moveL')"
    @move-r="emit('moveR')"
    @delete="emit('delete')"
    @select="emit('select', { node: _value.value })"
  />
</template>

<style scoped></style>
